<?php

/**
 * 同步百大订单数据
 */
namespace App\Service\OrderService;
use App\Service\BaseService;
use App\Model\BdOrderModel\BdOrderSub;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Model\CommodityModel\WarehouseInfo;
use App\Model\CommodityModel\SupplierCompany;
use App\Model\BdOrderModel\BdAddress;
use App\Model\BdUserModel\BdUser;
use App\Model\BdOrderModel\BdOrderProduct;
use App\Model\BdOrderModel\BdOrder;
use App\Model\CommodityModel\CommodityArchives;
use App\Model\CommodityModel\Stockinfo;
use App\Model\BdOrderModel\BdOrderLogistic;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\PssModel\OrderSupplierAmountExtra;
use App\Model\BdOrderModel\BdOrderLog;
use App\Model\PssModel\OrderSupplierLog;
use App\Model\BdOrderModel\BdOrderAfterSale;
use App\Model\PssModel\OrderRefund;
use App\Model\PssModel\OrderRefundGoods;
use App\Model\PssModel\OrderRefundLog;
use App\Model\BdOrderModel\BdOrderAfterSaleDetail;
use Hyperf\DbConnection\Db;
use App\Model\BdOrderModel\BdPaymentOrder;
use App\Model\BdOrderModel\BdOrderAfterSaleRemark;
class SyncBdOrderService extends BaseService
{
    /**
     * 同步百大订单功能
     */
    public function startSyncOrder() 
    {
        //$this->syncBdOrderSub();
        $this->syncBdOrderAfterSale();
    }
    
    /**
     * 同步子订单数据
     */
    public function syncBdOrderSub()
    {
        $limit = 400;
        $lastId = 3758362;
        $run_start_time = microtime(true);
        while ( true )
        {
            $list = BdOrderSub::instance()
            ->where('id','>',$lastId)       
            ->orderBy('id','asc')
            ->whereNotNull('attribute')
            ->limit($limit)
            ->get()
            ->toArray();
    
            if( empty($list) ) {
                break;
            }
            
            $endRow = end($list);
            $lastId = $endRow['id'];
            
            echo $lastId.PHP_EOL;
            $start_time = microtime(true);
            //仓库
            $warehouseCodes = array_column($list,'warehouseCode');
            $warehouseCodes = array_filter($warehouseCodes);
            $whDataMap = [];
            if( $warehouseCodes ) {
                $whData = WarehouseInfo::instance()->select(['WarehouseCode','ID'])->whereIn('WarehouseCode',$warehouseCodes)->get()->toArray();
                $whDataMap = array_column($whData,'ID','WarehouseCode');
            }

            
            //供应商
            $supplierCodes = array_column($list,'supplierCode');
            $supplierCodes = array_filter($supplierCodes);
            $supplierDataMap = [];
            if( $supplierCodes ) {
                $supplierData = SupplierCompany::instance()->select(['SupplierCode','ID'])->whereIn('SupplierCode',$supplierCodes)->get()->toArray();
                $supplierDataMap = array_column($supplierData,'ID','SupplierCode');
            }
            
            //处理省市区
            $provinceIds    = array_column($list,'provinceId');
            $cityIds        = array_column($list,'cityId');
            $districtIds    = array_column($list,'districtId');
            $addressIds     = array_merge($provinceIds,$cityIds,$districtIds);
            $addressIds     = array_filter(array_unique($addressIds));
            if( $addressIds ) {
               $addressList = BdAddress::instance()->whereIn('addressId',$addressIds)->get()->toArray();
               $addressMap = array_column($addressList,null,'addressId');
            }

            
            //获取所有用户的实名信息
            $userIds    = array_column($list,'uin');
            $userIds    = array_unique($userIds);
            $uinids     = BdUser::instance()->select(['uin','phone'])->whereIn('uin',$userIds)->get()->toArray();
            $uinidsMap  = array_column($uinids,null,'uin');
            
            
            //查询product 商品数据
            $omsPackageCodes = array_column($list,'omsPackageCode');
            $omsPackageCodes = array_filter($omsPackageCodes);
            $orderPackageProductsList = BdOrderProduct::instance()->whereIn('omsPackageCode',$omsPackageCodes)->get()->toArray();         
            $orderPackageProductsListMap = [];
            foreach ($orderPackageProductsList as $item) {
                $orderPackageProductsListMap[$item['omsPackageCode']][] = $item;
                unset($item);
            }
            
            //物流运单号
            $BdOrderLogisticList = BdOrderLogistic::instance()->whereIn('omsPackageCode',$omsPackageCodes)->get()->toArray();
            $BdOrderLogisticListMap = array_column($BdOrderLogisticList,null,'omsPackageCode');
            
            //查询主档案资料
            $productCodes = array_column($orderPackageProductsList,'productCode');
            $productCodeRows = CommodityArchives::instance()->select(['ID','SKUCode','BarCode','CommodityType'])->whereIn('SKUCode',$productCodes)->get()->toArray();
            $productCodeRowsMap = array_column($productCodeRows,null,'SKUCode');
            
            //查询供应商库存数据
            $stockInfoRows = Stockinfo::instance()
            ->select([
                'stock.ID',
                'stock.SpecList',
                'scb.SKUCode',
                'scb.IsHaveTaxRate',
                Db::raw("scb.ID as SupplierCommodityID")
            ])
            ->from('stockinfo_s2b as stock')
            ->join('suppliercommodity_s2b as scb','scb.ID','=','stock.SupplierCommodityID')
            ->whereIn('scb.SKUCode',$productCodes)->get()->toArray();
            $stockInfoRowsMap = array_column($stockInfoRows,null,'SKUCode');
            
            //查询出所有的主订单备注信息
            $orderNos = array_column($list,'orderNo');
            $orderList = BdOrder::instance()->select([
                'orderNo',
                'updateTime',
                'useMessage',
                'preTailPayNo',
                'preTailPayType',
                'payType',
                'payNo',
                'payTime',
                'prePeriod',
                'points',
                'pointsFee',//预售订单预付卡金额
                'depositPoints',//预售订单定金积分
                'depositPointsFee',//预售订单积分金额
                'depositPreCardFee',//预售订单定金预付卡金额
                'depositPayMoney',//预售订单定金支付金额
                'preCardFee',//预售订单预付卡金额
                'couponDeductFee',//预售订单优惠券金额
                'redPackDeductFee',//预售订单红包金额
                'ztDiscountAmount',//预售订单三方支付优惠金额
            ]
            )
            ->whereIn('orderNo',$orderNos)
            ->get()
            ->toArray();
            $orderListMap   = array_column($orderList,null,'orderNo');
            
            $endRow = end($list);
            $lastId = $endRow['id'];
            $insertBatchSupplierOrder = [];
            $insertBatchSupplierOrderGoods = [];
            $insertBatchSupplierOrderExtraMoney = [];
            $orderOmsMapIds = [];
            
            
            //寻找支付流水号
            $payNos = array_column($orderList,'payNo');//定金
            $payNos = array_unique($payNos);
            $orderPayNoRowMap = [];
            if( !empty($payNos))  {
                $orderPayNoRow = BdPaymentOrder::instance()->select(['batchno','payflowno','payFinishTime'])->whereIn('batchno',$payNos)->get()->toArray();
                $orderPayNoRowMap = array_column($orderPayNoRow,null,'batchno');
            }
            
            //寻找尾款支付流水号
            $preTailPayNos = array_column($orderList,'preTailPayNo');//尾款
            $preTailPayNos = array_unique($preTailPayNos);
            $orderTailPayNoRowMap = [];
            if( !empty($preTailPayNos))  
            {
                $orderTailPayNoRow = BdPaymentOrder::instance()->select(['batchno','payflowno','payFinishTime'])->whereIn('batchno',$preTailPayNos)->get()->toArray();
                $orderTailPayNoRowMap = array_column($orderTailPayNoRow,null,'batchno');
            }
            
            foreach ($list as $order)
            {
                //获取身份证信息
                $cardInfo = getIdCardInfo((string)$order['ordererIdCard']);
                
                //子订单号
                $omsPackageCode = $order['omsPackageCode'];
                //主订单号
                $orderNo        = $order['orderNo'];
                if( empty($orderPackageProductsListMap[$omsPackageCode]) ) {
                    continue;
                }
                
                $orderProductList = $orderPackageProductsListMap[$omsPackageCode];
                
                //获取主订单数据
                if( empty($orderListMap[$orderNo]) ) {
                    "未获取到主订单数据\r\n";
                    continue;
                }
                
                //销售总价
                $orderGoodsMoney    = '0.00';
                $costPriceTotal     = '0.00';
                foreach ($orderProductList as $product) 
                {
                    $salePrice          = $product['salePrice'];
                    $skuTaxation        = $product['skuTaxation'];
                    $buyCount           = $product['buyCount'];
                    //单个商品税金
                    $tax                = bcdiv($skuTaxation,$buyCount,2);
                    $salePrice          = bcadd($salePrice, $tax,2);
                    $singlePrice        = bcmul((string)$salePrice,(string)$buyCount,2);
                    //销售单价
                    $orderGoodsMoney    = bcadd($orderGoodsMoney, $singlePrice,2);
                    //供应商成本价
                    $singleCostPrice    = bcmul($product['costPrice'],$product['buyCount'],2);
                    $costPriceTotal     = bcadd($costPriceTotal, $singleCostPrice,2);
                }
                
                //订单类型
                $orderFrom          = $order['orderFrom'];
                //实际支付金额
                $real_total_money   = $order['otherPay'];
                
                //主订单信息
                $main_order = $orderListMap[$orderNo];
                
                //如果是预售订单的话，otherPay需要-减去定金字段
                if( $orderFrom == 3 ) {
                    //实际支付金额
                    $real_total_money   = bcsub($real_total_money,$main_order['depositPayMoney'],2);
                }
                
                //运费
                $deliver_money      = $order['logisticsFee'];                
                //订单总金额 = 商品运费 + 商品总金额
                $orderMoney         = bcadd($orderGoodsMoney,$deliver_money,2);                
                //优惠总金额
                $discount_money     = bcsub($orderMoney,$real_total_money,2);
                //orderRemarks
                $orderRemarks       = !empty($orderListMap[$orderNo]) ? $orderListMap[$orderNo]['useMessage'] : '';
                //仓库ID
                $store_id           = !empty($whDataMap[$order['warehouseCode']]) ? $whDataMap[$order['warehouseCode']] :  0 ;//仓库ID
                
                $status_arr = [
                    'WAITPAY'           => '待支付',
                    'WAITDELIVER'       => '待发货',
                    'OUT'               => '已出库',
                    'SIGN'              => '已签收',
                    'REFUNDINT'         => '退款中',
                    'REFUND'            => '已退款',
                    'FINISH'            => '已完成',
                    'CLOSE'             => '已关闭',
                    'AFTERSALESUBMIT'   => '售后单提交'
                ];
                
                //主订单信息
                if( !empty($orderListMap[$orderNo]) ) {
                    $orderInfo = $orderListMap[$orderNo];
                    $payType  = $orderInfo['payType'];
                    $payArry = [
                        'ALIPAY'    => [
                            'code'  => '31222699S7',
                            'name'  => '支付宝(中国)网络技术有限公司'
                        ],
                        'WX'    => [
                            'code'  => '4403169D3W',
                            'name'  => '财付通支付科技有限公司'
                        ],
                        'ALlIPAY'    => [
                            'code'  => '312228034T',
                            'name'  => '通联支付网络服务股份有限公司'
                        ],
                    ];
                    $extends = [
                        'paySerial'         => !empty($orderInfo['payNo']) ? $orderInfo['payNo'] : '',
                        'payCommanyName'    => !empty($payArry[$payType]) ? $payArry[$payType]['name'] : '',
                        'payCommanyCode'    => !empty($payArry[$payType]) ? $payArry[$payType]['code'] : '',
                        'enterpriseNum'     => '3401210027',
                        'enterpriseName'    => '安徽空港百大启明星跨境电商有限公司',
                        'idCardFrontImage'  => $order['cdFrontPackCode'],
                        'idCardBackImage'   => $order['cdAfterPackCode']
                    ];
                }
                
                //处理发货时间
                if( !empty($BdOrderLogisticListMap[$omsPackageCode]) ) {
                    $express_shipping_time = strtotime($BdOrderLogisticListMap[$omsPackageCode]['createTime']);
                } else {
                    $express_shipping_time = 0;
                }
                
                //订单售后状态
                $status = $order['status'];
                $after_sale_status_arr = $this->getOrderAfterStatus($status);                
                $order_id = IdService::instance()->getOmsID();
                $orderOmsMapIds[$omsPackageCode] = $order_id;
                $supplierOrder = [
                    'id'                        => $order_id,
                    'order_sn'              	=> $order['omsPackageCode'],
                    'supplier_psn'          	=> $orderNo,
                    'supplier_csn'          	=> $order['omsPackageCode'],
                    'supplier_dsn'              => $order['omsPackageCode'],
                    'order_status'              => $this->getOrderStatus($status),
                    'order_push_status'         => $this->getOrderPushStatus($order['systemStatus']),
                    'order_push_remark'         => $order['pushMsg'],
                    'order_push_system_status'  => $order['systemStatus'],
                    'after_sale_status'         => $after_sale_status_arr['after_status'],
                    'after_verify_status'       => $after_sale_status_arr['verify_status'],
                    'company_id'                => !empty($supplierDataMap[$order['supplierCode']]) ? $supplierDataMap[$order['supplierCode']] : 0,
                    'bid'                   	=> 1,
                    'order_type'                => 0,
                    'order_trade_type'          => $this->getOrderTradeType($order['orderFrom']),
                    'company_type'              => 1,
                    'channel_id'                => 1,
                    'is_channel'                => 1,
                    'store_id'              	=> $store_id,
                    'buyer_realname'        	=> $order['ordererRealName'],			//下单人
                    'buyer_phone'           	=> !empty($uinidsMap[$order['uin']]) ? $uinidsMap[$order['uin']]['phone'] : '',				//下单人电话
                    'buyer_idcard'          	=> $order['ordererIdCard'],				//下单人身份证号
                    'buyer_sex'                 => $cardInfo['sex'],//性别
                    'buyer_age'                 => $cardInfo['age'],//年龄
                    'buyer_id_volid'            => $cardInfo['is_volid'],
                    'receive_name'          	=> $order['receiver'],//收货人姓名
                    'recveive_phone'        	=> $order['receiverTel'],//收货人电话
                    'province'              	=> !empty($addressMap[$order['provinceId']]) ? $addressMap[$order['provinceId']]['addressName'] : '',					//省
                    'city'                  	=> !empty($addressMap[$order['cityId']]) ? $addressMap[$order['cityId']]['addressName'] : '',						//市
                    'district'              	=> !empty($addressMap[$order['districtId']]) ? $addressMap[$order['districtId']]['addressName'] : '',					//区
                    'receive_address'       	=> $order['address'],			                   //收货地址
                    'pay_money'                 => $real_total_money,
                    'pay_status'                => !empty($orderInfo) && !empty($orderInfo['payTime']) ? 1 : 0 ,
                    'pay_time'                  => !empty($orderInfo) && !empty($orderInfo['payTime']) ? strtotime($orderInfo['payTime']) : 0 ,
                    'order_money'           	=> $order['otherPay'],		                       //订单金额
                    'goods_money'           	=> $order['goodsFee'],                             //商品金额
                    'deliver_money'         	=> $deliver_money,                                 //运费金额
                    'discount_money'        	=> $discount_money,                                //优惠金额
                    'total_money'           	=> $orderMoney,                                    //订单金额
                    'invoice_money'         	=> '0.00',                                         //发票金额
                    'real_total_money'      	=> $real_total_money,                              //实付金额
                    'costprice'                 => $costPriceTotal,                                //供应商成本价
                    'settlement_total_money'    => '0.00',                                         //商户结算价格
                    'order_remark'          	=> $orderRemarks,                                  //订单备注
                    'order_source'              => 'bdyg',                                         //订单来源
                    'origin_order_id'           => 0,                                              //原始订单id
                    'origin_supplier_dsn'       => 0,                                              //原始订单号
                    'is_split_order'            => 0,                                              //是否拆单
                    'tax'                   	=> '0.00',                              	       //订单总税费
                    'express_sn'                => $order['logisticsNo'],
                    'express_code'              => $order['logisticsCom'],
                    'express_name'              => $order['logisticsCom'],
                    'express_shipping_time'     => $express_shipping_time,
                    'cd'                    	=> time(),
                    'is_order_declare'          => 0,
                    'is_pay_declare'            => 1,
                    'is_child_system'           => 0,
                    'is_top_system'             => 1,
                    'is_query_express'          => 0,
                    'total_template_delivery'   => '0.00',
                    'delivery_template_info'    => json_encode([], JSON_UNESCAPED_UNICODE),//地区运费模板
                    'is_seckill'                => 0,
                    'is_supplier_settlement'    => 0,
                    'is_channel_settlement'     => 0,
                    'is_encrypt_order'          => 0,
                ];
                
                $insertBatchSupplierOrder[] = $supplierOrder;

                //优惠金额字段部分
                $surplusDiscount        = $order['surplusDiscount'];
                $avgDiscount            = $order['avgDiscount'];
                $avgPointFee            = $order['avgPointFee'];
                $avgPoint               = $order['avgPoint'];
                $avgPreCardFee          = $order['avgPreCardFee'];
                $superCouponDeductFee   = $order['superCouponDeductFee'];
                $avgZtDiscountAmount    = empty($order['avgZtDiscountAmount']) ? '0.00' : $order['avgZtDiscountAmount'];
                
                //计算优惠总金额
                $totalDiscountMoney = bcadd((string)$surplusDiscount,(string)$avgDiscount,2);
                $totalDiscountMoney = bcadd((string)$totalDiscountMoney,(string)$avgPointFee,2);
                $totalDiscountMoney = bcadd((string)$totalDiscountMoney,(string)$avgPreCardFee,2);
                $totalDiscountMoney = bcadd((string)$totalDiscountMoney,(string)$superCouponDeductFee,2);
                $totalDiscountMoney = bcadd((string)$totalDiscountMoney,(string)$avgZtDiscountAmount,2);
                
                
                //处理支付数据
                $payNo = $main_order['payNo'];
                $preTailPayNo = $main_order['preTailPayNo'];
                
                //定金
                $deposit_pay_sn = '';
                $deposit_pay_time = 0;
                if( !empty($orderPayNoRowMap[$payNo]) ) {
                    $deposit_pay_sn = $orderPayNoRowMap[$payNo]['payflowno'];
                    $deposit_pay_time  = !empty($orderPayNoRowMap[$payNo]['payFinishTime']) ? strtotime($orderPayNoRowMap[$payNo]['payFinishTime']) : 0;
                }
                
                //尾款
                $final_pay_sn = '';
                $final_pay_time = 0;
                if( !empty($orderTailPayNoRowMap[$preTailPayNo]) ) {
                    $final_pay_sn   = $orderTailPayNoRowMap[$preTailPayNo]['payflowno'];
                    $final_pay_time = !empty($orderTailPayNoRowMap[$preTailPayNo]['payFinishTime']) ? strtotime($orderTailPayNoRowMap[$preTailPayNo]['payFinishTime']) : 0;
                }
                
                //写入优惠金额明细
                //订单其它消费金额扩展表
                $insertBatchSupplierOrderExtraMoney[] = [
                    'order_id'                      => $order_id,
                    'deposit_mode'                  => 1,
                    'deposit_sn'                    => $payNo,
                    'deposit_pay_sn'                => $deposit_pay_sn,
                    'deposit_money'                 => $main_order['depositPayMoney'],
                    'deposit_thirdparty_money'      => empty($order['ztDiscountAmount']) ? '0.00' : $order['ztDiscountAmount'],
                    'deposit_advance_money'         => $main_order['depositPreCardFee'],
                    'deposit_points_money'          => $main_order['depositPointsFee'],
                    'deposit_points'                => $main_order['depositPoints'],
                    'deposit_pay_time'              => $deposit_pay_time,
                    'deposit_pay_way'               => $main_order['payType'],
                    'final_sn'                      => $preTailPayNo,
                    'final_pay_sn'                  => $final_pay_sn,
                    'final_money'                   => $real_total_money,//尾款支付金额
                    'final_thirdparty_money'        => $avgZtDiscountAmount,
                    'final_advance_money'           => $avgPreCardFee,
                    'final_points_money'            => $avgPointFee,
                    'final_points'                  => $avgPoint,
                    'final_red_envelope_money'      => $avgZtDiscountAmount,
                    'final_pay_time'                => $final_pay_time,
                    'final_pay_way'                 => $main_order['preTailPayType'],
                    'discount_money'                => $totalDiscountMoney,
                    'discount_points_money'         => $avgPointFee,
                    'discount_red_envelope_money'   => $superCouponDeductFee,
                    'discount_activity_money'       => $avgDiscount,
                    'discount_activity_name'        => '优惠活动',
                    'discount_coupon_money'         => $surplusDiscount,
                    'discount_coupon_names'         => '优惠卷',
                    'discount_payway_money'         => $avgZtDiscountAmount,
                    'discount_red_envelope_name'    => '抵扣红包',
                    'order_pre_sale_stage'          => !empty($orderInfo['prePeriod']) ? $orderInfo['prePeriod'] : '0',
                    'order_precard_balance_money'   => '0.00',
                    'order_points'                  => !empty($orderInfo['points']) ? $orderInfo['points'] : '0.00',
                    'cd'                            => time(),
                ];
                
                //需要分摊商品订单运费
                $has_delivery_money = '0.00';
                $total_product_count = count($orderProductList);
                //商品总金额
                $goods_money = $supplierOrder['goods_money'];
                
                $has_surplusDiscount        = '0.00';
                $has_avgDiscount            = '0.00';
                $has_avgPointFee            = '0.00';
                $has_avgPreCardFee          = '0.00';
                $has_superCouponDeductFee   = '0.00';
                $has_discount_payway_money  = '0.00';
                
                //订单商品
                foreach ($orderProductList as $key => $product) 
                {
                    $productCode = $product['productCode'];
                    $buyCount    = $product['buyCount'];
                    $salePrice   = $product['salePrice'];
                    $skuTaxation = $product['skuTaxation'];
                    
                    //单个商品税金
                    $tax                = bcdiv($skuTaxation,$buyCount,2);
                    $salePrice          = bcadd($salePrice, $tax,2);
                    $goods_total_money  = (float)(bcmul((string)$salePrice,(string)$buyCount,2));
                    
                    //分摊运费
                    if( $key == $total_product_count - 1 ) 
                    {
                        $freight                        = bcsub((string)$deliver_money,(string)$has_delivery_money,2);
                        $discount_points_money          = bcsub((string)$avgPointFee,(string)$has_avgPointFee,2);
                        $discount_red_envelope_money    = bcsub((string)$superCouponDeductFee,(string)$has_superCouponDeductFee,2);
                        $discount_activity_money        = bcsub((string)$avgDiscount,(string)$has_avgDiscount,2);
                        $discount_coupon_money          = bcsub((string)$surplusDiscount,(string)$has_surplusDiscount,2);
                        $discount_payway_money          = bcsub((string)$avgZtDiscountAmount,(string)$has_discount_payway_money,2);
                        $discount_precard_money         = bcsub((string)$avgPreCardFee,(string)$has_avgPreCardFee,2);
                    } 
                    else
                    {
                        $scale_goods        = bcdiv((string)$goods_total_money, (string)$goods_money,4);
                        
                        $freight            = bcmul((string)$scale_goods, (string)$deliver_money,2);
                        $has_delivery_money = bcadd((string)$has_delivery_money,(string)$freight,2);
                        
                        $discount_points_money          = bcmul((string)$scale_goods, (string)$avgPointFee,2);
                        $has_avgPointFee                = bcadd((string)$has_avgPointFee,(string)$discount_points_money,2);
                        
                        $discount_red_envelope_money    = bcmul((string)$scale_goods, (string)$superCouponDeductFee,2);
                        $has_superCouponDeductFee       = bcadd((string)$has_superCouponDeductFee,(string)$discount_red_envelope_money,2);
                        
                        $discount_activity_money        = bcmul((string)$scale_goods, (string)$has_avgDiscount,2);
                        $has_avgDiscount                = bcadd((string)$has_avgDiscount,(string)$discount_activity_money,2);
                        
                        $discount_coupon_money          = bcmul((string)$scale_goods, (string)$surplusDiscount,2);
                        $has_surplusDiscount            = bcadd((string)$has_surplusDiscount,(string)$discount_coupon_money,2);
                        
                        $discount_payway_money          = bcmul((string)$scale_goods, (string)$avgZtDiscountAmount,2);
                        $has_discount_payway_money      = bcadd((string)$has_discount_payway_money,(string)$discount_payway_money,2);
                        
                        $discount_precard_money         = bcmul((string)$scale_goods, (string)$avgPreCardFee,2);
                        $has_avgPreCardFee              = bcadd((string)$has_avgPreCardFee,(string)$discount_precard_money,2);
                    }
                    
                    //单个商品实际优惠总金额
                    $discount_money = bcadd($discount_points_money, $discount_red_envelope_money,2);
                    $discount_money = bcadd($discount_money, $discount_activity_money,2);
                    $discount_money = bcadd($discount_money, $discount_coupon_money,2);
                    $discount_money = bcadd($discount_money, $discount_payway_money,2);
                    $discount_money = bcadd($discount_money, $discount_precard_money,2);
                    
                    //获取批次库存
                    $stock              = $stockInfoRowsMap[$productCode] ?? [];
                    $SpecList           = !empty($stock) ? @json_decode($stock['SpecList'],true) : [] ;
                    $SpecificationNum   = !empty($SpecList) ? current($SpecList)['SpecificationNum'] : 0;
                    
                    $isHaveTaxRate          = !empty($stock) ? $stock['IsHaveTaxRate'] : 1 ;
                    $stockInfoID            = !empty($stock) ? $stock['ID'] : 1 ;
                    $supplierCommodityID    = !empty($stock) ? $stock['SupplierCommodityID'] : 0 ;
                    $insertBatchSupplierOrderGoods[] = [
                        'id'                        	=> IdService::instance()->getOtherID(),
                        'bid'                       	=> 1,
                        'order_id'                      => $order_id,
                        'goods_id'                  	=> !empty($productCodeRowsMap[$productCode]) ? $productCodeRowsMap[$productCode]['ID'] : 0,
                        'goods_name'                	=> $product['productName'],
                        'barcode'                   	=> !empty($productCodeRowsMap[$productCode]) ? $productCodeRowsMap[$productCode]['BarCode'] : '',
                        'skucode'                   	=> $productCode,
                        'supplier_skuid'            	=> $supplierCommodityID,
                        'supplier_skucode'          	=> $product['wmsSkuCode'],
                        'supplier_store_code'       	=> '',  //供应商仓库编码
                        'supplier_store_id'         	=> '',  //供应商仓库ID
                        'supplier_goods_type'       	=> !empty($productCodeRowsMap[$productCode]) ? $productCodeRowsMap[$productCode]['CommodityType'] : '0',  //供应商商品类型
                        'supplier_store_parameters' 	=> '',//仓库订单商品额外仓库数据
                        'is_supplier_combine_skuid' 	=> 0,  //是否是组合装商品（1-是，0-否）
                        'goods_type'                	=> !empty($productCodeRowsMap[$productCode]) ? $productCodeRowsMap[$productCode]['CommodityType'] : '0',
                        'image'                     	=> $product['productImg'],
                        'quantity'                  	=> $buyCount,
                        'spec_num'                  	=> $SpecificationNum ? $SpecificationNum : $buyCount,
                        'spec_name'                 	=> '',
                        'weight'                    	=> '0.000',                                                //重量单位g
                        'total'                     	=> $goods_total_money,                                     //商品总价
                        'price'                     	=> (float)$salePrice,							           //商品单价
                        'costprice'                 	=> bcdiv($product['costPrice'], $buyCount,2),             	                               //供应商成本价
                        'tax'                       	=> $product['skuTaxation'],                                //单商品总税费
                        'tax_rate'                  	=> bcdiv($product['skuTaxation'], $product['sellPrice'],3),//商品税率
                        'has_rate'                  	=> $isHaveTaxRate,                      //是否含税
                        'channel_has_rate'          	=> 0, //是否用户设置含税
                        'is_free_postfee'           	=> 1,//是否包邮
                        'freight'                   	=> $freight,                        //商品运费
                        'discount_money'                => $discount_money,                 //商品总优惠金额
                        'discount_point_money'          => $discount_points_money,          //商品积分优惠金额
                        'discount_red_envelope_money'   => $discount_red_envelope_money,    //商品红包优惠金额
                        'discount_activity_money'       => $discount_activity_money,        //商品活动优惠金额
                        'discount_coupon_money'         => $discount_coupon_money,          //商品优惠卡券金额
                        'discount_payway_money'         => $discount_payway_money,          //商品支付方式优惠金额
                        'discount_precard_money'        => $discount_precard_money,         //商品预付卡支付金额
                        'settlement_price'         		=> '0.00',//商户结算价格
                        'store_id'                 		=> $store_id, //仓库ID
                        'batch_no'                 		=> '基准批次',	 //批次号
                        'stock_id'                 		=> $stockInfoID, //库存ID
                        'cd'                       		=> time(),							//创建时间
                        'is_deduct_stock'          		=> 1,
                        'is_seckill'               		=> 0 ,
                        'is_seckill_info'          		=> '',
                        'is_setting_freight'       		=> 0,
                        'freight_template'         		=> 0,
                        'cost_post_fee'            		=> 0,
                        'is_hight_rate'            		=> 0,
                        'high_rate_warnning_price' 		=> '0.00',
                        'lower_rate'               		=> '0.000'
                    ];
                }
            }
            
            //获取所有订单日志
            $orderLogs = BdOrderLog::instance()->select(['omsPackageCode','content','operatTime','operator'])->whereIn('omsPackageCode',$omsPackageCodes)->get()->toArray();
            $insertBatchInterfaceOrderLog = [];
            foreach ($orderLogs as $log) 
            {
                $omsPackageCode = $log['omsPackageCode'];
                if( !empty($orderOmsMapIds[$omsPackageCode]) ) 
                {
                    $insertBatchInterfaceOrderLog[] = [
                        'order_supplier_id' => $orderOmsMapIds[$omsPackageCode],
                        'order_mode'        => 0,
                        'contents'          => $log['content'],
                        'system_user_id'    => 0,
                        'system_user_name'  => $log['operator'],
                        'cd'                => strtotime($log['operatTime']),
                    ];
                }
            }
            
            //写入订单快照数据
            if( !empty($insertBatchSupplierOrder) )
            {
                OrderSupplier::instance()->insert($insertBatchSupplierOrder);
                OrderSupplierAmountExtra::instance()->insert($insertBatchSupplierOrderExtraMoney);
                OrderSupplierGoods::instance()->insert($insertBatchSupplierOrderGoods);
                $pageOrderLog = array_chunk($insertBatchInterfaceOrderLog, 1000);
                foreach ($pageOrderLog as $orderLog) 
                {
                    OrderSupplierLog::instance()->insert($orderLog);
                }
            }
            
            echo "耗时：".bcsub((string)microtime(true),(string)$start_time,3) . "秒".PHP_EOL;
        }
        
        echo "总耗时：".bcsub((string)microtime(true),(string)$run_start_time,3) . "秒".PHP_EOL;
    }
    
    /**
     * 售后订单数据
     */
    public function syncBdOrderAfterSale()
    {
        $limit = 1000;
        $lastId = 0;
        $run_start_time = microtime(true);
        while ( true )
        {
            $list = BdOrderAfterSale::instance()
            ->where('id','>',$lastId)
            ->orderBy('id','asc')
            ->limit($limit)
            ->get()
            ->toArray();
            
            if( empty($list) ) {
                break;
            }
            
            $endRow = end($list);
            $lastId = $endRow['id'];
            echo $lastId.PHP_EOL;
            
            //查询原始子订单信息
            $omsPackageCodes    = array_column($list,'omsPackageCode');
            $omsPackageCodes    = array_filter($omsPackageCodes);
            $bdOriginOrderSubList     = BdOrderSub::instance()->whereIn('omsPackageCode',$omsPackageCodes)->get()->toArray();
            $bdOriginOrderSubListMap  = array_column($bdOriginOrderSubList,null,'omsPackageCode');
            
            //供应商信息
            $supplierCodes = array_column($bdOriginOrderSubList,'supplierCode');
            $supplierList = SupplierCompany::instance()->whereIn('SupplierCode',$supplierCodes)->get()->toArray();
            $supplierListMap = array_column($supplierList, null,'SupplierCode');
            
            //查询云仓子订单信息
            $omsPackageCodes        = array_column($list,'omsPackageCode');
            $omsPackageCodes        = array_filter($omsPackageCodes);
            $orderSupplierList      = OrderSupplier::instance()->select(['id','order_sn'])->whereIn('order_sn',$omsPackageCodes)->get()->toArray();
            $orderSupplierListMap   = array_column($orderSupplierList,null,'order_sn');
            
            //查询云仓子订单商品信息
            $orderIds = array_column($orderSupplierList,'id');
            $orderSupplierGoodsList = OrderSupplierGoods::instance()->select(['id','goods_type','skucode','supplier_skucode','price','spec_num','quantity','order_id'])->whereIn('order_id',$orderIds)->get()->toArray();
            $orderSupplierGoodsListMap = [];
            foreach ($orderSupplierGoodsList as $orderGoods) {
                $orderSupplierGoodsListMap[$orderGoods['order_id']][$orderGoods['skucode']] = $orderGoods;
                unset($orderGoods);
            }
            
            //查询售后订单商品信息
            $afterSalesNos = array_column($list,'afterSalesNo');
            $afterSalesGoodsList = BdOrderAfterSaleDetail::instance()->whereIn('afterSalesNo',$afterSalesNos)->get()->toArray();
            $afterSalesGoodsListMap = [];
            foreach ($afterSalesGoodsList as $afterOrderGoods) {
                $afterSalesGoodsListMap[$afterOrderGoods['afterSalesNo']][] = $afterOrderGoods;
                unset($afterOrderGoods);
            }
            
            //批量获取用户信息
            $userIds = array_column($list,'userId');
            $userIds = array_unique($userIds);
            $userList = BdUser::instance()->select(['uin','phone'])->whereIn('uin',$userIds)->get()->toArray();
            $userListMap = array_column($userList,null,'uin');
            $insertBatchRefundOrder = [];
            $insertBatchRefundOrderGoods = [];
            $insertBatchRefundOrderLog = [];
            
            //售后日志
            $BdOrderAfterSaleRemark = BdOrderAfterSaleRemark::instance()->whereIn('afterSalesNo',$afterSalesNos)->get()->toArray();
            $BdOrderAfterSaleRemarkMap = [];
            foreach ($BdOrderAfterSaleRemark as $item)
            {
                $BdOrderAfterSaleRemarkMap[$item['afterSalesNo']][] = [
                    'type'          => $item['type'],
                    'action'        => $item['action'],
                    'remark'        => $item['remark'],
                    'createTime'    => $item['createTime'],
                    'creator'       => $item['creator']
                ];
            }
            
            foreach ($list as $order)
            {
                //子订单号
                $omsPackageCode = $order['omsPackageCode'];
                //退款单号
                $order_refund_sn = $order['afterSalesNo'];
                //组装售后订单
                $order_refund_id = IdService::instance()->getOtherID();
                //获取售后订单状态-退款状态-审核状态
                $refundStatusArr = $this->getRefundStatus($order['status']);
                if( !empty($bdOriginOrderSubListMap[$omsPackageCode]) ) 
                {
                    $bdOrder = $bdOriginOrderSubListMap[$omsPackageCode];
                    $sub_order_status = $this->getOrderStatus($bdOrder['status']);
                    $company_id  = !empty($supplierListMap[$bdOrder['supplierCode']]) ? $supplierListMap[$bdOrder['supplierCode']]['ID'] : 0 ;
                    $logisticsNo = $bdOrder['logisticsNo'];
                    $real_total_money = $bdOrder['otherPay'];                    
                } else {
                    $sub_order_status = 0;
                    $company_id = 0;
                    $logisticsNo = '';
                    $real_total_money = 0;
                }
                
                if( !empty($orderSupplierListMap[$omsPackageCode]) )
                {
                    $orderSuppplier = $orderSupplierListMap[$omsPackageCode];
                    $sub_order_id = $orderSuppplier['id'];
                } else {
                    $sub_order_id = 0;
                }
                
                $refund_mode = $order['source'] == 'USER' ? 2 : 1;
                
                //会员ID
                $userId  = $order['userId'];
                $orderRefund = [
                    'id'                    => $order_refund_id,
                    'bid'               	=> 1,
                    'order_sn'          	=> $omsPackageCode,
                    'sub_order_sn'      	=> $omsPackageCode,
                    'sub_order_id'      	=> $sub_order_id,
                    'sub_order_status'  	=> $sub_order_status,
                    'sub_order_money'   	=> $real_total_money,
                    'supplier_id'       	=> $company_id,
                    'order_express_sn'      => $logisticsNo,
                    'refund_sn'         	=> $order_refund_sn,
                    'refund_source'         => 1,
                    'refund_type'       	=> $this->getRefundType($order['type']),
                    'refund_status'     	=> $refundStatusArr['refund_status'],
                    'refund_mode'       	=> $refund_mode,
                    'refund_reason_way' 	=> $this->getRefundReasonWay($order['refundReason']),
                    'refund_remark'         => $order['feedRemark'],
                    'refund_description'    => $order['description'],
                    'refund_attach'         => $order['attachImg'],
                    'reply_express_money'   => $order['hyFreight'],
                    'supplier_express_money'=> $order['refundFreight'],
                    'refund_deposit_otherpay_money' => (float)$order['depositRefundOtherPay'],
                    'refund_deposit_precard_money' => (float)$order['depositRefundPreCardFee'],
                    'refund_deposit_points_money' => (float)$order['depositRefundPointsFee'],
                    'refund_tail_otherpay_money' => (float)$order['tailRefundOtherPay'],
                    'refund_tail_precard_money' => (float)$order['tailRefundPreCardFee'],
                    'refund_tail_points_money' => (float)$order['tailRefundPointsFee'],
                    'refund_apply_money'    => (float)$order['refundTotalMoney'],
                    'refund_points_money'   => (float)$order['refundPointsFee'],
                    'refund_prepay_money'   => (float)$order['refundPreCardFee'],
                    'refund_envelope_money' => '0.00',
                    'refund_coupon_money'   => (float)$order['totalCouponFree'],
                    'refund_points_give'    => $order['returnPoints'],
                    'linkphone'             => !empty($userListMap[$userId]) ? $userListMap[$userId]['phone'] : '',
                    'refund_order_status'   => $refundStatusArr['refund_order_status'],
                    'refund_amount_status'  => $refundStatusArr['refund_amount_status'],
                    'financial_remark'      => $order['financeBack'],
                    'refund_amount_type'    => 1
                ];
                
                //退款单生成
                if( $orderRefund['refund_order_status'] == 1 ) {
                    $orderRefund['refund_order_sn']     = 'TK'.$order_refund_id;//退款订单号
                    $orderRefund['refund_order_time']   = !empty($order['refundTime']) ? $order['refundTime'] : null;
                } else {
                    $orderRefund['refund_order_sn']     = '';
                    $orderRefund['refund_order_time']   = null;
                }
               
                //扩展参数其它交易类型（钱买分等等三方需求功能）
                $needBuyCent = !empty($order['needBuyCent']) ? $order['needBuyCent'] : '0.00';
                if( $needBuyCent ) {
                    $orderRefund['refund_extra_mode']  = 1;
                    $orderRefund['refund_extra_value'] = json_encode([
                        'vipId'         => $userId,
                        'centToBuy'     => '0.00',
                        'cashMoney'     => $needBuyCent
                    ],JSON_UNESCAPED_UNICODE);
                } else {
                    $orderRefund['refund_extra_mode']  = 0;
                    $orderRefund['refund_extra_value'] = '';
                }
                
                $insertBatchRefundOrder[] = $orderRefund;
                
                $orderAfterGoods = $afterSalesGoodsListMap[$order_refund_sn];
                //组装售后商品记录
                foreach ($orderAfterGoods as $refundGoods)
                {
                    $productCode  = $refundGoods['productCode'];
                    //原始订单商品ID                    
                    if( !empty($orderSupplierGoodsListMap[$sub_order_id]) && !empty($orderSupplierGoodsListMap[$sub_order_id][$productCode]) ) 
                    {
                        $goods = $orderSupplierGoodsListMap[$sub_order_id][$productCode];
                        $goodsItemId        = $goods['id'];
                        $goods_type         = $goods['goods_type'];
                        $supplier_skucode   = $goods['supplier_skucode'];
                        $price              = $goods['price'];
                        $spec_num           = $goods['spec_num'];
                        $quantity           = $goods['quantity'];
                    }
                    else
                    {
                        $goodsItemId        = 0;
                        $goods_type         = 0;
                        $supplier_skucode   = '';
                        $price              = '0.00';
                        $spec_num           = 0;
                        $quantity           = 0;
                    }
                    
                    $insertBatchRefundOrderGoods[] = [
                        'id'                    => IdService::instance()->getOtherID(),
                        'bid'                   => 1,
                        'refund_order_id'       => $order_refund_id,
                        'goods_type'            => $goods_type,
                        'skucode'               => $productCode,
                        'supplier_skucode'      => $supplier_skucode,
                        'price'                 => $price,
                        'spec_num'              => $spec_num,
                        'buy_num'               => $quantity,
                        'refund_num'            => $refundGoods['num'],
                        'refund_useable'        => 1,
                        'cd'                    => strtotime($refundGoods['createTime']),
                    ];
                }
                
                if( !empty($BdOrderAfterSaleRemarkMap[$order_refund_sn]) ) 
                {
                    foreach ($BdOrderAfterSaleRemarkMap[$order_refund_sn] as $item) 
                    {
                        //售后来源方式：
                        $remark = $item['remark'];
                        $type = $item['type'];
                        $refund_after_remark = [
                            'AUTOREFUND'    => '自动退款',
                            'CUSTOMER'      => '客服操作',
                            'GOODSMONEY'    => '申请退款退货申请',
                            'MONEY'         => '仅退款申请',
                            'REFUND'        => '审核退款',
                            'TURNDOWN'      => '售后关闭'
                        ];
                        
                        $type_contents = !empty($refund_after_remark[$type]) ? $refund_after_remark[$type] : '';
                        $refund_mode_contents = OrderRefund::instance()->refund_mode[$refund_mode];
                        $contents = "售后订单方式[{$refund_mode_contents}],操作类型[$type_contents]，售后备注[{$remark}]";
                        
                        //写入订单日志
                        $insertBatchRefundOrderLog[] = [
                            'id'                => IdService::instance()->getOtherID(),
                            'order_refund_id'   => $order_refund_id,
                            'contents'          => $contents,
                            'system_user_id'    => 0,
                            'system_user_name'  => $item['creator'],
                            'cd'                => !empty($item['createTime']) ? strtotime($item['createTime']) : time(),
                        ];
                    }
                }
            }
            
            OrderRefund::instance()->insert($insertBatchRefundOrder);
            OrderRefundGoods::instance()->insert($insertBatchRefundOrderGoods);
            $logList = array_chunk($insertBatchRefundOrderLog,1000);
            foreach($logList as $logitems) 
            {
                OrderRefundLog::instance()->insert($logitems);
            }
        }
    }
    
    /**
     * 售后状态
     * `status` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '
     *  售后单状态 
     *  ADUITING:待客服审核 
     *  ADUITING_REPEAT:客服重复审核中 
     *  RETURNING_WAIT:请回邮商品 
     *  RETURNING:待客服确认回货 
     *  ADUITING_FINANCE:待财务审核
     *  REFUND_WAIT:待退款
     *  SUCCESS:退款成功 
     *  CLOSE:关闭',
     * @param unknown $status
     */
    public function getRefundStatus($status)
    {
        if( in_array($status,['ADUITING','ADUITING_REPEAT']) ) {
            return [
                'refund_status'         => 1,
                'refund_order_status'   => 0,
                'refund_amount_status'  => 0
            ];
        } else if( in_array($status,['RETURNING']) ) {
            return [
                'refund_status'         => 9,
                'refund_order_status'   => 1,
                'refund_amount_status'  => 0
            ];
        } else if( in_array($status,['RETURNING_WAIT']) ) {
            return [
                'refund_status'         => 5,
                'refund_order_status'   => 1,
                'refund_amount_status'  => 1
            ];
        } else if( in_array($status,['REFUND_WAIT']) ) {
            return [
                'refund_status'         => 2,
                'refund_order_status'   => 1,
                'refund_amount_status'  => 0
            ];
        } else if( in_array($status,['SUCCESS']) ) {
            return [
                'refund_status'         => 4,
                'refund_order_status'   => 1,
                'refund_amount_status'  => 1
            ];
        } else if( in_array($status,['CLOSE']) ) {
            return [
                'refund_status'         => 8,
                'refund_order_status'   => 0,
                'refund_amount_status'  => 0
            ];
        } else {
            return [
                'refund_status'         => 1,
                'refund_order_status'   => 0,
                'refund_amount_status'  => 0
            ];
        }
    }
    
    /**
     * 获取售后原因
     * 售后原因 
     * QUALITY:质量问题 
     * DAMAGED:商品破损 
     * INMATCH:实物与描述不符
     * OTHER:其它
     * @param unknown $reasonWay
     * 
     * 1-主动退款，2-7天无理由，3-拍错/多拍/不喜欢,4-未收到商品，5-协商一致退款，6-商品描述不符，7-商家发错商品，8-大小/颜色/型号不合适，9-质量问题,10-信息填错,11-三方退款
     */
    public function getRefundReasonWay($reasonWay)
    {
        if( in_array($reasonWay,['QUALITY','DAMAGED']) ) {
            return 9;
        } else if( in_array($reasonWay,['INMATCH']) ) {
            return 6;
        } else {
            return 11;
        }
    }
    
    /**
     * 获取售后单类型
     * 售后单类型 
     * GOODSMONEY:退货退款 
     * MONEY:退款
     * REFUSE:拒绝售后申请
     * PARTREFUND：部分退款
     * EXCHANGEGOODS：换货
     * @param $refundType
     */
    public function getRefundType($refundType)
    {
        if( in_array($refundType,['GOODSMONEY']) ) {
            return 1;
        } else if( in_array($refundType,['MONEY','PARTREFUND']) ) {
            return 2;
        } else if( in_array($refundType,['EXCHANGEGOODS']) ) {
            return 3;
        } else {
            return 0;
        }
    }
    
    /**
     * 获取订单交易类型
     * //订单交易模式类型（1-普通订单，2-卡券订单，3-预售订单，4-充值订单）
     * @param unknown $orderFrom
     */
    public function getOrderTradeType($orderFrom)
    {
        if( in_array($orderFrom,['5','8','11']) ) {
            return 3;
        } else if( in_array($orderFrom,['20']) ) {
            return 4;
        } else if( in_array($orderFrom,['10']) ) {
            return 2;
        } else {
            return 1;
        }
        
    }
    
    /**
     * 获取获取订单状态
     * //子订单状态，WAITPAY-待支付，WAITDELIVER-待发货，OUT-已出库，SIGN-已签收，REFUNDINT-退款中，REFUND-已退款，FINISH-已完成, CLOSE-已关闭，AFTERSALESUBMIT-售后单提交
     * @param unknown $status
     */
    public function getOrderStatus($status)
    {
        if( in_array($status,['WAITPAY','CLOSE']) ) {
            return 0;
        } else if( in_array($status,['WAITPAY']) ) {
            return 1;
        } else if( in_array($status,['OUT','SIGN','FINISH']) ) {
            return 2;
        } else {
            return 1;
        }
    }
    
    /**
     * 获取获取订单推送仓库状态
     * 系统状态，1-已审核，2-待推送仓库，3-推送仓库成功，4-推送仓库失败，5-待推送支付平台，6-推送支付平台成功，7-推送支付平台失败，8-待推送海关，9-推送海关成功，10-推送海关失败，11-待发货，12-已发货，13-已退款，14-已签收，15-已关闭，16-已完成'
     * @param unknown $status
     */
    public function getOrderPushStatus($status)
    {
        if( in_array($status,['3','8','9','10','11','12','13','14','16']) ) {
            return 1;
        } else if( in_array($status,['4']) ) {
            return 2;
        } else {
            return 0;
        }
    }
    
    /**
     * 获取获取售后状态
     * //子订单状态，REFUNDINT-退款中，REFUND-已退款，AFTERSALESUBMIT-售后单提交
     * @param $status
     */
    public function getOrderAfterStatus($status)
    {
        if( in_array($status,['WAITPAY','REFUND']) ) {
            return [
                'after_status'  => 1,
                'verify_status' => 1
            ];
        } else if( in_array($status,['AFTERSALESUBMIT']) ) {
            return [
                'after_status'  => 1,
                'verify_status' => 0
            ];
        } else {
            return [
                'after_status'  => 0,
                'verify_status' => 0
            ];
        }
    }
}
